<template>
  <div class="container">
    <div class="form-layout">
      <!--左侧导航-->
      <div class="nav-left">
        <customAnchor
          :itemList="[
            { name: 'box-base', title: '扫描' },
            { name: 'box-info', title: '库存信息' },
            { name: 'box-dtl', title: '库存明细' },
          ]"
        />
      </div>

      <!--表单区域-->
      <div class="form-right" ref="formRight">
        <div id="box-base" class="box-title">扫描</div>
        <customForm :data="form" ref="editForm" :rules="propRules"  :withRangeYMD="true">
          <template #content>
            <customTooltip>
              <template #title>
                请扫描SN或者RFID
              </template>
              <template #content>
                <FortenScan
                  ref="txtScan"
                  propPlaceholder="SN/RFID"
                  @after-scan="barCodeScan"
                  propType="uniqueCode"
                  style="width: 300px;margin-top: 10px;display: inline-block; margin-right: 5px"
                />
                <customButton title="打印标签" theme="primary" @click="print" :disabled="btnPrintDisabled" />
                <customButton title="重置" @click="initData" />
              </template>
            </customTooltip>
            <div class="alert">
              <t-alert theme="warning">
               <template #message> 扫描SN或者RFID标签进行检索，若存在库存，则可以进行绑定解绑操作 </template>
              </t-alert>
            </div>
            <div id="box-info" class="box-title">库存信息</div>
            <customFormItem label="商品名称" name="matrName" :parent="_self" :form="form" disabled />
            <customFormItem label="商品品规" name="matrSpec" :parent="_self" :form="form" disabled />
            <customFormItem label="供应商" name="supplierName" :parent="_self" :form="form" disabled  />
            <customFormItem label="批次" name="lot" :parent="_self" :form="form" disabled  />
            <customFormItem label="生产日期" name="mfgDate" :parent="_self" :form="form" disabled  />
            <customFormItem label="有效期" name="expDate" :parent="_self" :form="form" disabled  />
            <customFormItem label="包装单位" name="packageUnit" :parent="_self" :form="form" disabled  />
            <customFormItem label="包装单品数量" name="skuQty" :parent="_self" :form="form" disabled  />
            <customFormItem label="厂商" name="mfgName" :parent="_self" :form="form" disabled  />
            <customFormItem label="SN码" name="sn" :parent="_self" :form="form" disabled  />
            <customFormItem label="RFID" name="rfid" :parent="_self" :form="form" disabled  />

        </template>
      </customForm>

      <div id="box-dtl" class="box-title">库存明细</div>
      <data-view
        ref="dataViewSN"
        propViewKey="wm_stock_rfidbind"
        :propFlowKey="propFlowKey"
        :propAutoFetchData=false
        :propParentPage="_self"
        @extra-button-click="extraButtonClick"
        :propIsTdesign="true"
      />

    </div>
  </div>
</div>
</template>

<script>
import barcodeParse from '@/util/barcodeParse.js'
import customAnchor from '@/components/custom/form/customAnchor.vue'

export default {
  data() {
    return {
      form: {
        matrName: '',
        id: '',
        matrSpec: '',
        supplierName: '',
        lot: '',
        mfgDate: '',
        expDate: '',
        packageUnit: '',
        skuQty: '',
        mfgName: '',
        sn: '',
        rfid: ''
      },
      sn: '',
      btnPrintDisabled: true,
      // propInitData: [],
    }
  },
  name: 'rfidbind',
  mounted() {
    this.$refs.txtScan.focus()

    setTimeout(() => {
      this.initData()
    },500)
  },

  methods: {
    initData() {
      this.form = {}
      this.sn = ''
      this.fetchData()
      this.$refs.txtScan.focus()
    },

    //扫码SN或RFID
    barCodeScan(value) {
      /* eslint-disable*/
      //校验唯一码
      const txtScan = value
      if(!txtScan){
        this.$refs.txtScan.focus()
        this.initData()
        this.utilMessage.warning(" 请输入唯一码进行查询")
        return false
      }
      //校验唯一码得类别
      let codeType = barcodeParse.barCodeType(txtScan)
      console.log('codeType===', codeType)
      if(!codeType || (codeType != 'RFID' && codeType != 'SN' )){
        this.$refs.txtScan.focus()
        this.initData()
        this.utilMessage.error(" 唯一码【" + txtScan + "】类型非法")
        return false
      }
      if (codeType == 'SN') {
        this.$ajax.get(`wm/stock/getStockByUCOnly?uc=${txtScan}`).then((response) => {
          if (response.success) {
            if (response.data.warehouseId == this.utils.getCurrentWarehouse().id) { //仓库相同才可绑定
              this.utilMessage.success(response.msg)
              this.form = response.data
              this.sn = txtScan
              this.fetchData(txtScan, 'SN')
              this.btnPrintDisabled = false
              if(this.form.rfid) this.sn =''
            } else {
              this.utilMessage.error("该耗材不属于该仓库不允许绑定")
            }
          } else {
            this.initData()
          }
          this.utilVue.loadHide()
        })
      }
      if (codeType == 'RFID') {
        console.log('this.sn = ===', this.sn )
         this.$ajax.get(`wm/stock/getStockListByUniqueCode?uniqueCode=${txtScan}`).then((response) => {
          if (response.success) {
            if (response.data.length !== 0) {
              this.utilMessage.success(response.msg)
              this.form = response.data[0]
              this.sn = '';
              this.fetchData(txtScan, 'RFID')
            } else {
              if (this.sn) {
                this.$ajax.get(`wm/stock/rfidBindOrUnbind?opType=bind&sn=${this.sn}&rfid=${txtScan}`).then((response) => {
                  if(response.success){
                    this.utilMessage.success("绑定成功")
                    this.$set(this.form, 'rfid', txtScan)
                    this.fetchData(txtScan, 'RFID')
                    this.sn = '';
                  }
                })
              } else {
                this.initData()
                this.utilMessage.error("该RFID未绑定任何SN,请先扫描SN")
                this.$refs.txtScan.focus()
              }
            }
          }
        })
      }
    },

    extraButtonClick({ button, data, index }) {
      if (button.key === 'unbind') {
        this.unbind()
      }
    },

    //加载明细
   fetchData(value, codeType) {
      let queryWrapper = this.$newWrapper()
      if (codeType == 'SN') {
        queryWrapper.eq('sn', value)
      } else if (codeType == 'RFID') {
        queryWrapper.eq('rfid', value)
      } else {
        queryWrapper.ne(1, 1)
      }
      this.$refs.dataViewSN.setQueryWrapper(queryWrapper)
    },

    //解绑
     async unbind(){
       const result = await this.$confirm('是否解绑该RFID与SN绑定关系')
       if (!result) return

       this.utilVue.loadShow(true)
       this.$ajax.get(`wm/stock/rfidBindOrUnbind?opType=unbind&sn=${this.form.sn}&rfid=null` ).then((response) => {
         if(response.code == 0){
           this.utilMessage.success(response.msg)
           this.form.rfid = ''
           this.fetchData(this.form.sn, 'SN')
           this.$refs.txtScan.focus()
         }else{
           this.utilMessage.error(response.msg)
         }
         this.utilVue.loadHide()
       })
     },
     print() {
       if (strings.isNotBlank(this.form.rfid)){
         this.utilMessage.error("请先解绑RFID，再进行打印")
         return
       }
       let printer_label_serverid = localStorage.getItem('printer_label_serverid')
       let printer_label_server_type_key = localStorage.getItem('printer_label_server_type_key')
       if (printer_label_server_type_key != 'rfid') {
         this.utilMessage.error("请先到工作台选择RFID打印机")
         return
       }
       this.utilVue.loadShow(true)
       let params = {
         snArr: [],
         printerId: printer_label_serverid
       }
       params.snArr.push(this.form.sn)
       this.$ajax.post('/tool/printRFID', params, {timeout: 1000 * 60 * 10}).then(resp => {
         if (resp.code == 0) {
           this.utilMessage.success(resp.msg)
         }
         this.utilVue.loadHide()
       })
     }
  },
  components: {
    customAnchor,
  },
  props: {
    propParent: Object,
    propPrimaryKey: String,
    propDictionaries: Object,
    propCurrentRow: Object,
    propViewFormData: Object,
    propReadonly: Boolean,
    propStatus: String,
    propRules: Object,
    propFlowKey: String,
    propParam: Object
  },
 }
 </script>
 <style lang="scss" scoped>
  .alert {
    width: 100%;
    .t-alert {
      padding: 8px 5px !important;
    }
  }
  .form-right {
    background: #fff;
  }
 </style>
